<template>
  <TreeLayout @changeWorkshop="changeUnitPart" ref="workshopTree">
    <template slot="left-top-extra">
      <a-form :label-col="{ span: 24 }" :wrapper-col="{ span: 24 }" layout="inline">
        <a-row>
          <a-col span="24">
            <a-form-item label="用能类型" style="width: 100%">
              <j-dict-select-tag
                type="list"
                v-model="model.eneType"
                dictCode="ene_energy_type,type,id"
                placeholder="请选择用能类型"
                @change="getItem"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </template>
    <template slot="right-content">
      <a-card :bordered="false" style="margin-bottom:12px">
        <a-form layout="inline" @keyup.enter.native="searchData">
          <a-row :gutter="12">
            <a-col span="16">
              <a-form-item label="时间粒度">
                <date-range-radio key="energy" :mode="this.mode" :time.sync="time" :type.sync="queryParam.timetype"
                                  @changeData="searchData" @clearValue="clearValue"></date-range-radio>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </a-card>
      <a-card :bordered="false">
        <div style="display: flex;">
          <div id="echart" style="height: 360px;width: calc(100% - 350px)"></div>
          <div>
            <div style="text-align: center;font-size: 18px;color:#000;margin: 10px 0 20px 0;">能耗统计指标</div>
            <div style="display: flex;width:350px">
              <div
                style="box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.35);width:200px;height:100px;margin: 10px;border:1px solid #ccc;border-radius: 5px;overflow: hidden;">
                <div style="background-color: #ccc;text-align: center;padding:5px 0px;font-weight: 600;">累计能耗</div>
                <div
                  style="font-weight: 600;font-style: normal;font-size: 30px;color: #02A7F0;text-align: center;line-height: 70px;">
                  {{ model.total }}
                </div>
              </div>
              <div
                style="box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.35);width:200px;height:100px;margin: 10px;border:1px solid #ccc;border-radius: 5px;overflow: hidden;">
                <div style="background-color: #ccc;text-align: center;padding:5px 0px;font-weight: 600;">环比统计</div>
                <div
                  style="font-weight: 600;font-style: normal;font-size: 30px;color: #02A7F0;text-align: center;line-height: 70px;">
                  {{ model.qoq }}
                </div>
              </div>
            </div>
            <div style="display: flex;width:350px">
              <div
                style="box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.35);width:200px;height:100px;margin: 10px;border:1px solid #ccc;border-radius: 5px;overflow: hidden;">
                <div style="background-color: #ccc;text-align: center;padding:5px 0px;font-weight: 600;">环比%</div>
                <div
                  style="font-weight: 600;font-style: normal;font-size: 30px;color: #02A7F0;text-align: center;line-height: 70px;">
                  {{ model.qoqrate }}
                </div>
              </div>
              <div
                style="box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.35);width:200px;height:100px;margin: 10px;border:1px solid #ccc;border-radius: 5px;overflow: hidden;">
                <div style="background-color: #ccc;text-align: center;padding:5px 0px;font-weight: 600;">监测点数量
                </div>
                <div
                  style="font-weight: 600;font-style: normal;font-size: 30px;color: #02A7F0;text-align: center;line-height: 70px;">
                  {{ model.count }}
                </div>
              </div>
            </div>
          </div>
        </div>
        <div>
          <p style="font-size: 18px;color:#000;">数据报表</p>
          <a-table :columns="columns" :data-source="datas" bordered :scroll="{ x: scrollX }" size="middle">
            <template slot="name" slot-scope="text">
              <a>{{ text }}</a>
            </template>
          </a-table>
        </div>
      </a-card>
    </template>
  </TreeLayout>
</template>

<script>
import TreeLayout from '@/components/layouts/TreeLayout'
import moment from 'moment/moment'
import DateRangeRadio from '@comp/DateRangeRadio/DateRangeRadio'
import * as echarts from 'echarts'
import { getAction } from '@api/manage'

export default {
  name: 'Statistics',
  components: {
    TreeLayout,
    DateRangeRadio
  },
  data() {
    return {
      isopen: false,
      model: {
        eneType: '1787737587542962177',
        total: 0,
        qoq: 0,
        qoqrate: 0,
        count: 0
      },
      mode: 'all',
      time: moment(new Date(), 'YYYY-MM'),
      queryParam: {
        eneTypeId: '1787737587542962177',
        unitPartId: '1788431068226838529',
        timetype: 'month',
        time: moment().format('YYYY-MM')
      },
      columns: [],
      datas: []
    }
  },
  mounted() {
    this.searchData()
  },
  methods: {
    moment,
    changeUnitPart(value) {
      this.model.part = value
      this.queryParam.unitPartId = value
      this.searchData()
    },
    getItem() {
      this.searchData()
      this.modeFunc()
    },
    clearValue() {
      this.$set(this.queryParam, 'time', null)
    },
    searchData() {
      this.getTableData()
      // 设置时间格式和能源类型
      if (this.queryParam.timetype === 'quarter') {
        this.queryParam.time = moment(this.time).format('YYYY-Q');
      }
// 解析月份
      if (this.queryParam.timetype === 'month') {
        this.queryParam.time = moment(this.time).format('YYYY-MM')
      }

// 解析年度
      if (this.queryParam.timetype === 'year') {
        this.queryParam.time = moment(this.time).format('YYYY')
      }
      this.queryParam.eneTypeId = this.model.eneType
      getAction('/compute/eneRuleDataUnitpart/compute/result', this.queryParam).then(res => {
        /*var columns = [
          {
            title: '用能类型',
            dataIndex: 'energyName',
            fixed: 'left',
            width: 150
          },
          {
            title: '总计',
            dataIndex: 'total',
            fixed: 'left',
            width: 100
          }
        ];*/
        this.model.total = res.result.statis.map(t => t.total).reduce((a, b) => a + b, 0).toFixed(2)
        this.model.qoq = res.result.statisqoq.map(t => t.total).reduce((a, b) => a + b, 0).toFixed(2)
        this.model.qoqrate = Number.parseFloat(this.model.total) <= 0 ? 100 : ((Number.parseFloat(this.model.total) - Number.parseFloat(this.model.qoq)) / Number.parseFloat(this.model.total) * 100).toFixed(2)
        this.model.count = res.result.count

        var chartDom = document.getElementById('echart')
        var myChart = echarts.init(chartDom)
        var times = res.result.statis.map(t => t.computeTime)
        var option = {
          graphic: {
            type: 'text',
            left: 'center',
            top: 'middle',
            silent: true,
            invisible: res.result.statis.length != 0,
            style: {
              fi11: 'black',
              fontWeight: 'bold',
              text: '暂无数据',
              fontSize: '20px'
            }
          },
          color: ['#5aaef3', '#62d9ad', '#5b6e96', '#ffdc4c', '#ff974c', '#e65a56', '#6d61e4', '#0b46ff', '#23c2db', '#a7c609'],
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow',
              textStyle: {
                color: '#fff'
              }
            }
          },
          xAxis: {
            type: 'category',
            data: times
          },
          yAxis: {
            type: 'value',
            name: '能源消耗',
            nameTextStyle: {
              color: '#333',
              fontSize: 16
            },
            axisLine: {
              lineStyle: {
                color: '#666'
              }
            },
            axisLabel: {
              color: '#666',
              fontSize: 16
            },
            splitLine: {
              show: true,
              lineStyle: {
                color: '#ccc'
              }
            }
          },
          series: [
            {
              data: res.result.statis.map(t => t.total),
              type: 'line',
              barWidth: '30',
              name: '合计',
              itemStyle: {
                normal: {
                  color: '#f4cf0c'
                }
              }
            }
          ]
        }
        var types = new Set(res.result.statis.map(t => t.eneTypeId))
        // this.datas = []
        types.forEach(type => {
          let temp = res.result.statis.filter(t => t.eneTypeId === type)
          let energyName = res.result.types.filter(t => t.id === type)?.[0]?.type ?? ''
          let total = times.map(time => temp.filter(t => t.computeTime === time)?.[0]?.total ?? 0)
          option.series.push({
            data: total,
            type: 'bar',
            barWidth: '30',
            stack: '能耗',
            name: energyName
          })
          /*let row = {
            energyName,
            total: 0,
            width: 150
          }
          let totalAdd = 0;
          temp.forEach(t => {
            row[t.computeTime] = t?.total ?? 0
            totalAdd += Number.parseFloat(t?.total ?? 0)
          })
          row.total = totalAdd.toFixed(2)*/
          // this.datas.push(row)
        })

        /*times.forEach((time, index) => {
          let temp = {
            title: time !== null ? time.split('-').pop() : '',
            dataIndex: time
          };
          if (index !== times.length - 1 || times.length > 10) temp.width = 100
          columns.push(temp);
        })*/


        // if (times.length <= 0) columns = [];
        option && myChart.setOption(option, true)
        myChart.resize()
        // this.columns = columns;
      })
        .catch(error => {
          // 处理请求错误
          console.error('请求发生错误:', error);

          // 显示一个基本的无数据图表
          var chartDom = document.getElementById('echart');
          var myChart = echarts.init(chartDom);
          var option = {
            graphic: {
              type: 'text',
              left: 'center',
              top: 'middle',
              silent: true,
              style: {
                fill: 'black',
                fontWeight: 'bold',
                text: '请求失败，请稍后再试',
                fontSize: '20px'
              }
            },
            xAxis: { type: 'category', data: [] },
            yAxis: { type: 'value' },
            series: []
          };
          myChart.setOption(option, true);
          myChart.resize();
        });
      // 
      // String time, String timetype, String unitPartId, String eneTypeId
    },
    getTableData() {
      // 设置时间格式和能源类型
      if (this.queryParam.timetype === 'quarter') {
        this.queryParam.time = moment(this.time).format('YYYY-Q');
      }
// 解析月份
      if (this.queryParam.timetype === 'month') {
        this.queryParam.time = moment(this.time).format('YYYY-MM')
      }

// 解析年度
      if (this.queryParam.timetype === 'year') {
        this.queryParam.time = moment(this.time).format('YYYY')
      }
      this.queryParam.eneTypeId = this.model.eneType

      if (this.queryParam.eneTypeId === '1792827463741640706' || this.queryParam.eneTypeId === '1787737587542962177') {
        getAction('/compute/eneRuleDataUnitpart/compute/resultClass', this.queryParam).then(res => {
          // 初始化列
          var columns = [
            { title: '用能类型', dataIndex: 'energyName', fixed: 'left', width: 100 },
            { title: '班组', dataIndex: 'team', fixed: 'left', width: 80 },
            { title: '总计', dataIndex: 'total', fixed: 'left', width: 100 }
          ];

          // 初始化数据数组
          this.datas = [];

          // 定义班次数组
          const shifts = ['一班', '二班', '三班'];

          // 用于收集所有唯一的 computeTime
          const uniqueTimesSet = new Set();

          // 遍历班次数组
          shifts.forEach(shift => {
            // 获取当前班次的数据
            const shiftData = res.result.statis[shift] || [];
            const shiftTypes = new Set(shiftData.map(t => t.eneTypeId));

            // 遍历能源类型，为每个能源类型创建一个数据行
            shiftTypes.forEach(type => {
              const typeData = shiftData.filter(t => t.eneTypeId === type);
              const energyName = res.result.types.find(t => t.id === type)?.type || '';
              let total = typeData.reduce((sum, t) => sum + (t.total || 0), 0);

              // 初始化当前行的数据（包括用能类型、班组和总计）
              let row = {
                energyName,
                team: shift,
                total: total.toFixed(2),
                // 初始化具体时间的列数据为0（后续会根据数据动态赋值）
                ...typeData.reduce((acc, t) => {
                  acc[t.computeTime] = 0;
                  uniqueTimesSet.add(t.computeTime); // 添加唯一的 computeTime
                  return acc;
                }, {})
              };

              // 遍历当前能源类型的数据，为具体时间的列赋值
              typeData.forEach(t => {
                row[t.computeTime] = (row[t.computeTime] || 0) + (t.total || 0);
              });

              // 将当前行添加到数据数组中
              this.datas.push(row);
            });
          });

          // 将 Set 转换为数组并排序
          const uniqueTimes = [...uniqueTimesSet].sort();

          // 动态添加具体时间的列到表格列中（去重并排序）
          uniqueTimes.forEach(time => {
            columns.push({
              title: time !== null ? time.split('-').pop() : '',
              dataIndex: time
            });
          });

          // 设置表格的列
          this.columns = columns;
        }).catch(error => {
          console.error('接口请求失败:', error);
          // 清空数据报表
          this.columns = [];
          this.datas = [];
        });
      }else {
        getAction('/compute/eneRuleDataUnitpart/compute/result', this.queryParam).then(a => {
          var columns = [
            {
              title: '用能类型',
              dataIndex: 'energyName',
              fixed: 'left',
              width: 150
            },
            {
              title: '总计',
              dataIndex: 'total',
              fixed: 'left',
              width: 100
            }
          ];
          const times = a.result.statis.map(t => t.computeTime)
          const types = new Set(a.result.statis.map(t => t.eneTypeId))
          this.datas = []
          types.forEach(type => {
            let temp = a.result.statis.filter(t => t.eneTypeId === type);
            let energyName = a.result.types.filter(t => t.id === type)?.[0]?.type ?? "";
            let row = {
              energyName,
              total: 0,
              width: 150
            }
            let totalAdd = 0;
            temp.forEach(t => {
              row[t.computeTime] = t?.total ?? 0
              totalAdd += Number.parseFloat(t?.total ?? 0)
            })
            row.total = totalAdd.toFixed(2)
            this.datas.push(row)
          })

          times.forEach((time, index) => {
            let temp = {
              title: time !== null ? time.split('-').pop() : '',
              dataIndex: time
            };
            if (index !== times.length - 1 || times.length > 10) temp.width = 100
            columns.push(temp);
          })
          if (times.length <= 0) columns = [];
          this.columns = columns;
        }).catch(error => {
          console.error('接口请求失败:', error);
          // 清空数据报表
          this.columns = [];
          this.datas = [];
        });
      }
      // 发送请求获取数据
    },
    modeFunc() {
      if (['1788817810812387329'].includes(this.model.eneType)) {
        this.mode = 'year'
        this.queryParam.timetype = 'year'
      } else this.mode = 'all'
      //
      this.searchData()
    },
    computed: {},
    scrollX() {
      return this.columns.reduce((preVal, curVal) => {
        return preVal + curVal.width
      }, 0)
    }
  }
}
</script>

<style scoped>
.ant-table-bordered .ant-table-fixed-right table {
  border-left: none;
}
</style>